const {app, screen, BrowserWindow, Menu, nativeImage, ipcMain, Tray} = require('electron');
const path = require('node:path');
const fs = require("fs");

let countdownWindow, countdownSettingWindow;
const countdownWindowWidth = 320, countdownWindowHeight = 100;
const countdownSettingWindowWidth = 600, countdownSettingWindowHeight = 300;


// Handle creating/removing shortcuts on Windows when installing/uninstalling.
// if (require('electron-squirrel-startup')) {
//   app.quit();
// }

// 创建窗口
// 1. 创建倒计时窗口
const createCountdownWindow = () => {
    countdownWindow = new BrowserWindow({
        width: countdownWindowWidth,
        height: countdownWindowHeight,
        frame: false,
        skipTaskbar: true,
        titleBarStyle: 'hidden',
        transparent: true,
        webPreferences: {
            // preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
            // contextIsolation: false,
        },
    });
    // 开启调试工具
    // countdownWindow.webContents.openDevTools({mode: 'detach'});
    // 当右键点击窗口时，显示自定义菜单
    const contextMenu = Menu.buildFromTemplate([
        {
            label: '重置', role: 'normal', click: function (menuItem, browserWindow, event) {
                countdownWindow.webContents.send('reset-countdown');
            }
        },
        {
            label: '设置', role: 'normal', click: function (menuItem, browserWindow, event) {
                const position = browserWindow.getPosition();
                const countdownSettingWindow = createCountdownSettingWindow();
                countdownSettingWindow.setPosition(position[0] - (countdownSettingWindowWidth - countdownWindowWidth), position[1] + 100);
            }
        },
        {type: 'separator'},
        {label: '退出', role: 'quit'}
    ]);
    countdownWindow.setResizable(false);
    countdownWindow.loadFile('src/html/countdown.html').then(() => {
        countdownWindow.setAlwaysOnTop(true, 'pop-up-menu');
        // 将窗口固定到最右边
        countdownWindow.setPosition((screen.getPrimaryDisplay().workAreaSize.width - countdownWindow.getSize()[0]), 0);
        // 当右键点击窗口时，显示自定义菜单
        countdownWindow.webContents.on('context-menu', (e, params) => {
            contextMenu.popup({window: countdownWindow, x: params.x, y: params.y});
        });
    });
    return countdownWindow;
}
// 2. 创建倒计时设置窗口
const createCountdownSettingWindow = () => {
    countdownSettingWindow = new BrowserWindow({
        width: countdownSettingWindowWidth,
        height: countdownSettingWindowHeight,
        frame: false,
        skipTaskbar: true,
        titleBarStyle: 'hidden',
        webPreferences: {
            // preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
            // contextIsolation: false,
        },
    });
    // countdownSettingWindow.webContents.openDevTools({mode: 'detach'});
    countdownSettingWindow.loadFile('src/html/countdown_setting.html').then(() => {
        countdownSettingWindow.setAlwaysOnTop(true);
    });
    return countdownSettingWindow;
}

// 其他辅助方法
const setAppSetting = (module, key, value) => {
    const settingPath = path.join(app.getPath('userData'), 'setting.json');
    let data = '';
    try {
        data = fs.readFileSync(settingPath, 'utf8').toString();
    } catch (e) {
    }
    if (!data || !data.length) {
        const jsonData = {}
        jsonData[`${module}`] = {[`${key}`]: value}
        // 如果读取文件失败，直接创建新文件，然后写入内容
        fs.writeFileSync(settingPath, JSON.stringify(jsonData));
        return;
    }
    let jsonData = {};
    try {
        jsonData = JSON.parse(data);
    } catch (e) {
    }
    let moduleSetting = jsonData[`${module}`];
    if (moduleSetting) {
        moduleSetting[key] = value;
        jsonData[`${module}`] = moduleSetting;
    } else {
        jsonData[`${module}`] = {[`${key}`]: value}
    }
    fs.writeFileSync(settingPath, JSON.stringify(jsonData));
};
const getAppSetting = (module) => {
    const settingPath = path.join(app.getPath('userData'), 'setting.json');
    try {
        const data = fs.readFileSync(settingPath, 'utf8').toString();
        if (!data || !data.length) {
            return {};
        }
    } catch (e) {
        // 如果读取文件出错，返回空对象
        return {};
    }
    let jsonData = {};
    try {
        jsonData = JSON.parse(data);
    } catch (err) {
        return {};
    }
    return jsonData[`${module}`];
}

app.whenReady().then(() => {
    //上面创建窗体代码省略
    countdownWindow = createCountdownWindow()
    const icon = nativeImage.createFromPath(path.join(__dirname, 'image', 'favicon.ico'))
    let tray = new Tray(icon)
    const contextMenu = Menu.buildFromTemplate([
        {
            label: '主界面', type: 'normal', click: (menuItem, browserWindow, event) => {
                if (countdownWindow === undefined) {
                    countdownWindow = createCountdownWindow()
                } else {
                    countdownWindow.show()
                }
            }
        },
        {
            label: '退出', type: 'normal', click: (menuItem, browserWindow, event) => {
                app.quit();
            }
        },
    ])
    tray.setContextMenu(contextMenu)
    tray.setToolTip('办公助手')
    //托盘双击
    tray.on('double-click', (event) => {
        countdownWindow.show()
    })

    // 监听来自渲染进程的close-countdown-setting-window消息
    ipcMain.on('close-countdown-setting-window', () => {
        countdownSettingWindow.close();
    });
    ipcMain.on('submit-countdown-setting', (event, settings) => {
        countdownSettingWindow.close();
        countdownWindow.webContents.send('countdown-setting-change', settings);
    });
    ipcMain.handle('set-app-setting', (event, module, key, value) => {
        setAppSetting(module, key, value);
    });
    ipcMain.handle('get-app-setting', (event, module) => {
        return getAppSetting(module);
    });
    //   // On OS X it's common to re-create a window in the app when the
    //   // dock icon is clicked and there are no other windows open.
    //   app.on('activate', () => {
    //     if (BrowserWindow.getAllWindows().length === 0) {
    //       createWindow();
    //     }
    //   });
});

// // Quit when all windows are closed, except on macOS. There, it's common
// // for applications and their menu bar to stay active until the user quits
// // explicitly with Cmd + Q.
// app.on('window-all-closed', () => {
//   if (process.platform !== 'darwin') {
//     app.quit();
//   }
// });
